package com.xiaoyu.lanling.feature.guard.data

import `in`.srain.cube.request.JsonData
import `in`.srain.cube.request.RequestDefaultHandler
import `in`.srain.cube.views.list.PagedListDataModelWithRequestTag
import android.text.TextUtils
import com.xiaoyu.base.net.RequestCreator
import com.xiaoyu.lanling.common.config.HttpConfig
import com.xiaoyu.lanling.event.guard.GuardListEvent
import com.xiaoyu.lanling.feature.guard.datamodel.BaseGuardItem
import com.xiaoyu.lanling.feature.guard.datamodel.GuardItem
import com.xiaoyu.lanling.feature.guard.datamodel.MyGuardItem

class GuardListData(private val requestTag: Any, type: String) : PagedListDataModelWithRequestTag<BaseGuardItem, Any>() {

    companion object {
        val TYPE_GUARD = "guard"
        val TYPE_MY_GUARD = "my_guard"
    }

    val isMyGuard = TextUtils.equals(type, TYPE_MY_GUARD)
    val url = if (isMyGuard) HttpConfig.LANLING_GUARD_GET_MY_GUARD_LIST else HttpConfig.LANLING_GUARD_GET_GUARD_ME

    override fun doQueryData() {
        RequestCreator.create(GuardListEvent::class.java)
                .setRequestUrl(url)
                .appendQueryDataTo(listPageInfo)
                .setRequestHandler(object : RequestDefaultHandler<GuardListEvent, JsonData>() {

                    override fun processOriginData(originData: JsonData): GuardListEvent {
                        val rawData = originData.optJson("data")
                        val list = mutableListOf<BaseGuardItem>()

                        for (item in rawData.optJson("list").toList()) {
                            list.add(if (isMyGuard) MyGuardItem(item) else GuardItem(item))
                        }

                        updateResult(rawData, list)

                        return GuardListEvent(requestTag)
                    }

                    override fun onRequestFinish(event: GuardListEvent) {
                        event.post()
                    }
                })
                .enqueue()
    }

    override fun getRequestTag(): Any {
        return requestTag
    }
}